
/**
 * 登录模块，提供登录相关业务功能
 *
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "datagridServ","ajaxServ","msgServ","sysmanMain", "bizProto","btnServ","flowServ","panelUtil","flowHistoric"],
		function($,datagridServ,ajaxServ,msgServ, sysmanMain, bizProto,btnServ,flowServ,panelUtil,flowHistoric) {

			'use strict';

			var _bizProto,_moduleConfig,_buttonConfig,_defaultConfig,
				//锚记datagrid目标元素
				$dg,
				//初始化后的datagrid dom对象
				$grid,
				//编辑弹窗对象及弹窗按钮对象
				$edit_window,$edit_window_height=700,$edit_window_width=700,window_btn,

				//流程执行信息grid
				_historicGrid,
				//业务表单对象
				$form,

				//字段配置url
				field_url = '/flowTaskConfig/query/getTaskConfig.action',
				_config ={
					doc:null,
					rootId:null,
					panelSelector:'div.well',
					subSystemCode:null,
					moduleCode:null,
					editWindow:null,
					editbtnSelector:'div.flow-edit-btn',
					initQueryParams:null,
					initElement:null,
					historicUrl:null,
					initParam:{editable:true},
					historicField:null,
					buttonExtends:null,
					fieldSetting:null//流程字段验证
				}
				
				,
				//业务配置
				_bizconfig
					
					



			var public_method = {
				
				//设置业务代码
				setBizConfig:function(_options){
					_bizconfig = _options;
				}
				,
				
				init:function(_options){

					
					
					_moduleConfig = private_method.getCurrentModuConf();
					
					
					if (window.console && _moduleConfig) {
						console.info( _moduleConfig.fullBizcode + ' modules gets ready and been loaded.');
					}


					_defaultConfig = $.extend({},_config,_moduleConfig,_options)
					_bizProto = new bizProto(_defaultConfig);
					_bizProto.gridHeight -= 15

					_defaultConfig.bizProto=_bizProto




					if(_defaultConfig.editWindow){
						$edit_window = $('#'+_defaultConfig.editWindow)
						_moduleConfig.edit_window = _defaultConfig.editWindow
					}

					_buttonConfig={
						 "保存":private_method.submit,
						 "取消":private_method.cancel,
						 "发送":private_method.flowSend,
						 "回退":private_method.flowBack,
						 "签收":private_method.flowSign
					}
					if(_defaultConfig.buttonExtends){
						var _extends = _defaultConfig.buttonExtends()
						if(_extends)
						$.extend(_buttonConfig,_extends)
					}

					_defaultConfig.buttonConfig = _buttonConfig
					//保存模块初始化信息
					sysmanMain.setModuConf(_defaultConfig.fullBizcode,_defaultConfig)
					private_method.init();
				}

			}

			var private_method = {


				//初始化元素
				init : function() {


					var _tab = sysmanMain.getCurrentTab();
					$grid = $(_tab).find("table.dg-list");

					var selectedRecord
					if(_defaultConfig.data){
						selectedRecord = _defaultConfig.data
					}else{

						selectedRecord=$grid.datagrid('getSelected');
					}
					var _fullBizcode 
					if(_bizconfig && _bizconfig.fullBizcode){
						_fullBizcode = _bizconfig.fullBizcode
					}else{
						_fullBizcode = sysmanMain.getCurrentBizcode();
					}

					//页面字段控制
					var task_config_url = _bizProto.rootPath + field_url;
					var task_param = {fullBizcode:_fullBizcode}
					if(selectedRecord ){

						//根据流程节点状态判断是否可编辑
						if(selectedRecord.flowStatus){

							if(selectedRecord.flowStatus===2 || selectedRecord.flowStatus===3){
								var _iparam = {initParam:{}}
								if(!_defaultConfig.initParam)
									_defaultConfig.initParam={editable:true}
								else{
									_defaultConfig.initParam.editable=true
								}
							}else{
								_defaultConfig.initParam.editable = false
							}
						}else{
							_defaultConfig.initParam.editable = false
						}
					}
					if(_defaultConfig.initParam && _defaultConfig.initParam.editable){

						//字段必填项初始化
						if(selectedRecord && selectedRecord.task_def_key)
							task_param.activityId=selectedRecord.task_def_key
						$.ajax({
							url:task_config_url,
							data:task_param,
							type : 'post',
							success:private_method.fieldSetting
						})

						var editTd = $($edit_window).find(_defaultConfig.editbtnSelector)

						//判断功能按钮是否显示


						// 编辑窗口初始化
						if(editTd && editTd.length>0){
							var _param = {
								bizcode:_fullBizcode,
								rootPath:_bizProto.rootPath,
								container:editTd,
								callback:private_method.bindBtnEvent}
							btnServ.generateEditBtn(_param);
						}
					}
					// 编辑窗口初始化
					$form = $($edit_window).find('form.main-form')
					$form.form('clear')




					//页面初始化参数
					var _initParam = {form:$form}
					//加载流程执行信息

					if(selectedRecord){

						$form.form('load',selectedRecord)
						_historicGrid= $($edit_window).find('div.historics')

						if(_historicGrid.length==0)
							_historicGrid= $($edit_window).find('table.historics')
						//判断流程table是否存在
						if(_historicGrid && _historicGrid.length>0){

							var _historicParam ={
								record:selectedRecord,
								historicId:_historicGrid
							}
							//判断流程调用方法
							if(_defaultConfig.historicUrl && _defaultConfig.historicField){
								//配置了url与流程字段，外部流程
								_historicParam.url = _defaultConfig.historicUrl
								var _field = _defaultConfig.historicField
								var _fieldValue = selectedRecord[_defaultConfig.historicField]
								_hisQryParam[_field]=_fieldValue
								_historicParam.queryParams = _hisQryParam
								if(window.console){
									console.info(' fieldName:' +  _field +',fieldValue:'+_fieldValue)
								}
								flowHistoric.initExternalGrid(_historicParam)
							}else{
								//内部流程方法调用

								flowHistoric.initInternalGrid(_historicParam)
							}

						}
						//判断是否调用组件初始化方法
						_initParam.record=selectedRecord
					}

					if(_defaultConfig.editWindow){
						_initParam.rootId= _defaultConfig.editWindow
					}
					//判断是否执行页面初始化
					if(_defaultConfig.initElement){_defaultConfig.initElement(_initParam)}
				},

				//绑定按钮事件
				bindBtnEvent:function(){

					window_btn = $($edit_window).find('a.function-btn')
					$(window_btn).unbind('click')
					$(window_btn).bind('click',	private_method.function_btn_listenner)

				},

				// 功能按钮监听函数
				function_btn_listenner : function(e) {
					
					btnServ.applyButton({buttonEvt:e,buttonConfig:_buttonConfig})

				},

				// 提交form
				submit : function(e) {
					if (window.console) {
						console.info('bugEdit submit on air ...');
					}
					var _param = {form:$form,grid:$grid,url:_bizProto.flowSaveUrl}
					if(_moduleConfig.flowid){
						_param.flowid = _moduleConfig.flowid
					}
					
					//提交前执行的函数
					if(_moduleConfig.beforeSubmit){
						_param.externalValue = _moduleConfig.beforeSubmit()
					}
					if(_moduleConfig.fullBizcode){
						_param.fullBizcode = _moduleConfig.fullBizcode
					}
					datagridServ.save(_param,e)
				},
				//
				cancel : function(e) {
					$($edit_window).window('close');
				},
				//签收
				flowSign:function(e){
					var isOpend = private_method.getOperatePanelState();
					if(!isOpend){
						private_method.changeOperatePanelState(1);
						return
					}
					var _data = private_method.getFlowMsg();
					if(_data && _data.signInfo){
						$.extend(_data,{refreshGrid:_historicGrid,flowSignUrl:_bizProto.flowSignUrl})
						flowServ.sign(_data);
					}else{
						msgServ.Msgslide('请填写签收意见')
					}

				},
				//发送
				flowSend:function(e){

					var _param = {form:$form,refreshGrid:$grid,flowTaskCompleteUrl:_bizProto.flowTaskCompleteUrl,closeWindow:$edit_window}
					if(_moduleConfig.flowid){
						_param.flowid = _moduleConfig.flowid
					}
					if(_moduleConfig.fullBizcode){
						_param.fullBizcode = _moduleConfig.fullBizcode
					}
					//提交前执行的函数
					if(_moduleConfig.beforeSubmit){
						_param.externalValue = _moduleConfig.beforeSubmit()
					}
					

					var _data = private_method.getFlowMsg();
					if(_data){
						$.extend(_data,_param)
						flowServ.taskComplete(_data,e);
					}
				},

				//回退
				flowBack:function(e){

					var _param = {form:$form,refreshGrid:$grid,flowSendbackUrl:_bizProto.flowSendbackUrl,closeWindow:$edit_window}
					if(_moduleConfig.flowid){
						_param.flowid = _moduleConfig.flowid
					}
					if(_moduleConfig.fullBizcode){
						_param.fullBizcode = _moduleConfig.fullBizcode
					}

					var _data = private_method.getFlowMsg();
					if(_data){
						$.extend(_data,_param)
						
						flowServ.sendBack(_data,e);
					}
				},
				getFlowMsg:function(){
					var _data = {},taskElement,signElement,instElement
					_moduleConfig = private_method.getCurrentModuConf();
					if(_moduleConfig.editWindow){
						$edit_window = $('#'+_moduleConfig.editWindow)
						instElement =$($edit_window).find('form.main-form #flowInstId')
						taskElement =$($edit_window).find('form.main-form #flowTaskId')
						signElement =$($edit_window).find('fieldset.form-operator input.signInfo')
						_data = {flowInstId:$(instElement).val(),flowTaskId:$(taskElement).val(),signInfo:$(signElement).val()}
					}

					return _data;
				},

				/**
				 * get the flow operate panel state
				 */
				getOperatePanelState:function(){
					_moduleConfig = private_method.getCurrentModuConf();
					if(_moduleConfig.editWindow){
						var flowOperatePanel = $('#'+_moduleConfig.editWindow +' div.flow-operate-panel')
						if(flowOperatePanel && flowOperatePanel.length>0){
							return panelUtil.getPanelState({target:flowOperatePanel})
						}
					}
				},

				/**
				 * @param state 1,open panel;0,close panel
				 */
				changeOperatePanelState:function(state){
					_moduleConfig = private_method.getCurrentModuConf();
					if(_moduleConfig.editWindow){
						var flowOperatePanel = $('#'+_moduleConfig.editWindow +' div.flow-operate-panel')
						if(flowOperatePanel && flowOperatePanel.length>0){
							if(state){
								$(flowOperatePanel).panel('open')
								private_method.getTransitionInfo();
							}else{
								$(flowOperatePanel).panel('close')
							}
						}
					}
				},
				/**
				 * 获取流程下一节点信息
				 */
				getTransitionInfo:function(){
					var flowInfo = private_method.getFlowMsg()
					if(flowInfo && flowInfo.flowInstId){
						_moduleConfig = private_method.getCurrentModuConf();
						if(_moduleConfig.editWindow){
							var $nodeSelect = $('#'+_moduleConfig.editWindow +' div.flow-operate-panel form.flow-operate-form #flownode')
							if($nodeSelect && $nodeSelect.length>0){
								$($nodeSelect).combobox({
									url:_moduleConfig.bizProto.rootPath + '/flowOperator/findTaskOutgoing.action?procInstId='+flowInfo.flowInstId,
									valueField:'id',
									textField:'name'
								})
							}
						}
					}

				},
				fieldSetting:function(data){

					_moduleConfig = private_method.getCurrentModuConf();
					if(data){
						if(_moduleConfig.fieldSetting){
							_moduleConfig.fieldSetting({data:data,form:$form})
						}

						var _f = data.editFilter

						var fields

						if(_f && _f.enabled){
							//旧模块流程定义配置模式
							fields = _f.enabled.split(',')
						}else{
							//新模块流程定义配置模式
							if(data.requiredFilter){
							fields = data.requiredFilter.split(',')
							}
						}

						if(fields && (fields.length>0)){

							for(var i =0;i<fields.length;i++){
								var _el =$($form).find('#' + fields[i])
								if(_el.length>0){
									 $(_el).attr('data-options','required:true')

								}
							}
							$($form).form('enableValidation').form('validate')
						}
					}
				}
				,
				/**
				 * 切换panel
				 * @param _options.targetPanel	待打开的panel
				 * 
				 */
				changePanel:function(_options){
					var _default = {
						editPanel :' div.edit-panel',
						uploadPanel :' div.upload-panel',
						historicPanel:' div.historic-panel',
						diagramPanel:' div.diagram-panel'
					}
					
					_moduleConfig = private_method.getCurrentModuConf();
					
					//判断传入targetPanel 是否存在
					var _targetPanel
					if(_options && _options.targetPanel && _default[_options.targetPanel]){
						_targetPanel = $('#' +_moduleConfig.edit_window +_default[_options.targetPanel] )
					}					
					
					//查找当前页面所有toggle-panel
					var $panels = $('#'+ _moduleConfig.edit_window +' div.toggle-panel' )
					
					//隐藏其他panel，显示目标panel
					if($panels.length>0 && _targetPanel.length>0){						
						$($panels).panel('close')						
						$(_targetPanel).panel('open')
					}					
				}
				,
				uploadInit:function(){
					_moduleConfig = private_method.getCurrentModuConf();
					
					/**
					 * 根据审核状态判断是否显示按钮栏
					 */
					var showToolBar = true
					if(_moduleConfig.auditEnable){
						if(buttonEvent.checkAuditStatus({editWindow:_moduleConfig.edit_window})){
							showToolBar = false
						}						
					}
					$edit_window = $('#'+ _moduleConfig.edit_window);
					var isSaved = false,_id
					var _idEl = $('#' + _moduleConfig.edit_window + ' form.main-form #id')
					if(_idEl.length==1){
						_id = $(_idEl).val()
						if(_id){
							isSaved = true
						}
					}
					
					if(!isSaved){
						msgServ.Msgslide('保存后才能上传附件');
						return
					}
					private_method.changePanel();
					var _uploadList = $('#' + _moduleConfig.edit_window + ' div.upload-panel div.table-archive')
					
					var _moduleCode
					if(_moduleConfig.typeRow){
						_moduleCode = _moduleConfig.typeRow.bizcode
					}else{
						_moduleCode = 	_moduleConfig.moduleCode
					}
					if(_uploadList.length>0){
						var selectedRecord = private_method.getCurrentDetailRecord()
						var uploadParam = {
							data:{
								bizno:_id,
								bizcode:_moduleCode
							},
							rootPath:_bizProto.rootPath,
							biztableid:_moduleConfig.edit_window + ' div.upload-panel div.table-archive',
							toolbarid : _moduleConfig.edit_window +' div.upload-panel div.archive-btn a.file_upload_btn'
						}						
						
						uploadfiles.initList(uploadParam)
						
						if(_moduleConfig.moduleCode && _id ){
						
							uploadfiles.init({
								data:{
									bizno:_id,
									bizcode:_moduleCode
								},
								queue_id:_moduleConfig.edit_window + ' div.upload-panel form.upload-form #queue',
								file_id:_moduleConfig.edit_window + ' div.upload-panel form.upload-form #file_upload',
								rootPath:_moduleConfig.bizProto.rootPath,
								rootid:_moduleConfig.edit_window})
						}
						
						
					}
				}
				
				,
				//获取当前模块配置
				getCurrentModuConf:function(){
					if(_bizconfig){
						return _bizconfig
					}else{
						return sysmanMain.getCurrentModuConfig();
					}
				}


			};

			return public_method;

		});
